/**
 * 配置请求
 */
// 导入模块
import qs from "qs";

// URL地址 - 这边是接口的前缀 - 根据实际情况自行引入
import config from "@/configs/server";

import { message } from "antd";

const BASE_URL = config.BASE_URL;

/** 封装fetch请求 */
function sendFetch(url:string, params:Object|null = null, method = "GET") {
  return new Promise(async (resolve, reject) => {
    // 配置的参数
    let config = {}
    config = {
      headers: {
        Authorization: localStorage.getItem("login_token") || "",
      },
    };
    // 判断请求类型
    if (method.toUpperCase() === "GET" || method.toUpperCase() === "DELETE") {
      if (params) {
        url += "?" + qs.stringify(params);
      }
    } else if (
      method.toUpperCase() === "POST" ||
      method.toUpperCase() === "PUT"
    ) {
      config = {
        method,
        headers: {
          "Content-Type": "application/json",
          ...config.headers,
        },
      };
      if (params) {
        config = {
          ...config,
          body: JSON.stringify(params),
        };
      }
    }

    try {
      const response = await fetch(BASE_URL + url, {
        mode: "cors",
        ...config,
      });
      response
        .json()
        .then((res) => {
          if (res.code == 2001) {
            window.history.replaceState(null, "", res.to);
            window.location.reload();
            return;
          } else if (res.code == 2002) {
            message
              .info({
                content: res.message,
                duration: 2,
                type: "error",
              })
              .then(() => {
                window.history.replaceState(null, "", res.to);
                window.location.reload();
              });
            return;
          }
          if (res.message) {
            message.info(res.message);
          }
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    } catch (error) {
      reject(error);
    }
  });
}

// 导出配置好的对象
export default sendFetch;
